package com.xlh.job;

import cn.hutool.core.io.FileUtil;
import com.xlh.dao.courseTest.CourseTestPaperAnswerMapperExt;
import com.xlh.dao.courseTest.CourseTestPaperMapperExt;
import com.xlh.dao.courseTest.CourseTestPaperQuestionMapperExt;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.service.courseTest.PaperAnswerSheetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * 试卷定时任务，用于回收已删除的试卷内容
 *
 * @author zhr 2019/3/15
 */
@Component
public class PaperGCTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(PaperGCTask.class);

    @Autowired
    private CourseTestPaperMapperExt mapperExt;
    @Autowired
    private CourseTestPaperQuestionMapperExt questionMapperExt;
    @Autowired
    private CourseTestPaperAnswerMapperExt answerMapperExt;
    @Autowired
    private PaperAnswerSheetService answerSheetService;

    /**
     * 每天凌晨1点执行题库定时清理任务
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void repositoryClean() {
        LOGGER.info("开始执行考试定时清理任务");

        // 清理服务器静态文件
//        cleanFiles();

        // 清理试卷数据库表的脏数据
//        cleanPaperDetails();

        LOGGER.info("执行考试定时清理任务完毕");
    }

    private void clearAnswerSheetCache() {
        answerSheetService.clearCache();
    }

    private void cleanPaperDetails() {
        questionMapperExt.cleanData();
        answerMapperExt.cleanData();
    }

    private void cleanFiles() {
        File[] paperDirs = FileUtil.ls(LocalResourcesEnum.PAPER.getLocalUploadPath());
        List<Long> allPaperId = mapperExt.selectAllPaperId();
        for (File paperDir : paperDirs) {
            if (allPaperId.contains(getPaperId(paperDir))) FileUtil.del(paperDir);
        }
    }

    private Long getPaperId(File paperDir) {
        String paperDirPath = FileUtil.normalize(paperDir.getPath());
        return Long.valueOf(paperDirPath.substring(paperDirPath.lastIndexOf('/') - 1));
    }
}
